package com.apes.fn.scm.retailReturn;

import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 功能：销售订单
 *
 * @author xul
 * @create 2018-01-25 19:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = RetailReturn.CONST_TABLE_NAME)
public class RetailReturn extends Model {
    public static final String CONST_TABLE_NAME = "retail_return";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "零售退回", prefix = "%(yy)%(month)", padding = 4, useDateRange=true)
    private String id;

    @States(name = "订单类型", values = {
            @State(id = "A", name = "有原单退货"),
            @State(id = "B", name = "无原单退货")})
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "order_type", referencedColumnName = "id", nullable = false)
    private BusinessAttributeValue orderType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "move_type", referencedColumnName = "id")
    @Comment("交货方式")
    private Enumeration moveType; //交货方式：("direct", "部分交货"), ("one", "一次性交货");

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("部门")
    private Dept dept;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "clerk_id", referencedColumnName = "id")
    @Comment("业务员")
    private PartyRole clerk;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id", referencedColumnName = "id")
    @Comment("客户")
    private PartyRole customer; //客户

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;

    @Transient
    private Map customerCar;


    public Map getCustomerCar() {
        if (customerExpand == null || customerExpand.getCarLicense() == null) return null;
        return MapUtil.mapper(
                "carLicense", customerExpand.getCarLicense(),
                "vendorCode", customerExpand.getVendorCode(),
                "customer", this.getCustomerInfo()
        );
    }

    @Transient
    private Map customerInfo;

    public Map getCustomerInfo() {
        if (customerExpand == null || customerExpand.getMobile() == null) return null;
        return MapUtil.mapper(
                "realname", customerExpand.getRealname(),
                "vendorCode", customerExpand.getVendorCode(),
                "mobile", customerExpand.getMobile()
        );
    }
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="sale_id", referencedColumnName="id")
    @Comment("原订单")
    private RetailOrder saleOrder;

    @Column(name = "origin", length = 30)
    @Comment("源单据")
    private String origin;

//    @Column(name = "remark", length = 120)
//    @Comment("订单备注")
//    private String remark;

    @Column(name = "return_reason", length = 120)
    @Comment("退款原因")
    private String returnReason;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "return_reasons", referencedColumnName = "id")
    @Comment("退货原因")
    private Enumeration returnReasons;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID; //审核

    @Column(name = "date_approve")
    @Comment("审批日期")
    private Date dateApprove;

    @Column(name = "date_done")
    @Comment("完成日期")
    private Date dateDone;

    @Column(name = "date_planned")
    @Comment("计划日期")
    private Date datePlanned;

    @Column(name = "date_cancel")
    @Comment("取消日期")
    private Date dateCancel;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_uid", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteUID; //删除

    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate; //删除日期

    @Column(name = "date_Sinopec_Return")
    @Comment("中石化退款完成日期")
    private Date dateSinopecReturn;

    @States(name = "订单状态", values = {
            @State(id = "sent", name = "退货申请"),
            @State(id = "sinopecReturn", name = "发起中石化退款"),
            @State(id = "confirmed", name = "审核"),
            @State(id = "refund", name = "退款"),
            @State(id = "done", name = "已完成")})
    @Column(name = "state", length = 16, nullable = false)
    private String state = "sent";

    @Column(name = "is_shipped", nullable = false)
    @Comment("已交货")
    private boolean shipped = false;

    @Column(name = "invoice_status", length = 10, nullable = false)
    @Comment("开票状态")
    private String invoiceStatus = "no"; //账单状态: ("no", "没有开票"), ("to_invoice", "开票中"), ("invoiced", "开票完成")

    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double amtTax = 0;

    @Column(name = "amt_untaxed", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税金额")
    private double amtUntaxed = 0;

    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double amtTotal = 0;

    @Column(name = "process_initiator")
    @Comment("流程发起人")
    private String processInitiator;

    @Column(name = "process_initiating_department")
    @Comment("流程发起人部门")
    private String processInitiatingDepartment;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<RetailReturnItem> saleItems = new HashSet(); //订单行

    public Set<RetailReturnItem> getSaleItems() {
        for (RetailReturnItem item : saleItems) {
            // 去除数量为 0 的行
            if (item.getProductUomQty() == 0) {
                saleItems.remove(item);
                continue;
            }
            item.setOrder(this);
            item.setCompany(this.company);
        }
        return saleItems;
    }

    /**
     * 功能: 判断当前单据是否需要收货
     */
    @Transient
    @States(name = "需要收货", values = {
            @State(id = "yes", name = "需收货"),
            @State(id = "no", name = "无需收货")})
    private String needShip;

    public String getNeedShip() {
        Set<RetailReturnItem> saleReturnItems = this.saleItems.stream()
                .filter(saleReturnItem -> saleReturnItem.getQtyDelivered() > 0)
                .collect(Collectors.toSet());
        return saleReturnItems.isEmpty() ? "no" : "yes";
    }

    @Comment("需退款标记")
    @Column(name = "refund")
    private String refund = "no";

    public void computeAmt() {
        amtUntaxed = 0; amtTax = 0;
        for (RetailReturnItem item : saleItems) {
            item.computeAmt();
            amtUntaxed += item.getPriceSubtotal();
            amtTax += item.getPriceTax();
        }
        amtTotal = amtUntaxed + amtTax;
    }

    /**
     * 功能：设置订单交货状态
     */
    public void setShipped() {
        long result = getSaleItems().stream()
                .filter(orderItem -> orderItem.getProductUomQty() != orderItem.getQtyDeliver()
                        && LogicalUtil.notIn(orderItem.getProduct().getType(), "aut"))
                .count();
        if (result == 0) {
            setShipped(true);
            setState();
        }
    }

    /**
     * 功能：设置订单状态
     */
    public void setState() {
        if (!state.equals("confirmed")) return;
        if (shipped) {
            setState("refund");
        }
    }
    /**
     * 功能：判断是否需要发货
     * 无需发货直接设置单据为退款状态
     */
    public void checkShip() {
        long result = getSaleItems().stream()
                .filter(orderItem -> LogicalUtil.in(orderItem.getProduct().getType(), "aut"))
                .count();
        if (result == getSaleItems().size()|| getNeedShip().equals("no")) {
            if (!state.equals("confirmed")) return;
                setState("refund");
        }
    }
}
